<?php

error_reporting(E_ERROR);

define('_DOC_ROOT', $_SERVER['DOCUMENT_ROOT']);

require_once _DOC_ROOT . '/src/php/Db.php';

class PUtil {

    static $fileList;
    static $root;

    public static function getFilePath($dir, $toFolder = true) {
        PUtil::$fileList = array();
        PUtil::$root = _DOC_ROOT . $dir;
        PUtil::_readDir(PUtil::$root , $toFolder);
        return PUtil::$fileList;
    }

    public static function _readDir($root, $toFolder) {
        $handle = opendir($root);
        if ($handle) {
            while ((false !== $file = readdir($handle))) {
                if ($file != '.' && $file != '..' && !preg_match('/svn/', $file)) {
                    if ($toFolder) {
                        if (is_dir($root . '/' . $file)) {
                            array_push(PUtil::$fileList, PUtil::trimRoot($root . '/' . iconv('GBK','UTF-8',$file)));
                            PUtil::_readDir($root . '/' . $file, $toFolder);
                        }
                    } else {
                        array_push(PUtil::$fileList, PUtil::trimRoot($root . '/' . iconv('GBK','UTF-8',$file)));
                        if (is_dir($root . '/' . $file)) {
                            PUtil::_readDir($root . '/' . $file, $toFolder);
                        }
                    }
                }
            }
            closedir($handle);
        } else {
            return;
        }
    }

    public static function trimRoot($path) {
        return str_replace(PUtil::$root . '/', "", $path);
    }

    public static function getFileList2Array($ary,$filter){
        $filterAry = array();
        is_array($filter) ? $filter = implode('|', $filter) : null;
        $filter = '(' . $filter . ')';
        foreach($ary as $val){
            if(!preg_match('/' . $filter . '/', $val)){
                array_push($filterAry, $val);
            }
        }
        return $filterAry;
    }

    /*
     * 获取请求的参数数据
     * @param   {array|string}  $key 参数字段
     * @return  关联数组
     */

    public static function getParams($key) {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            if (is_array($key)) {
                $rs = array();
                foreach ($key as $v) {
                    $post = $_POST[$v];
                    if (isset($post)) {
                        $rs[$v] = $post;
                    }
                }
                return $rs;
            } else {
                return $_POST[$key];
            }
        } else {
            if (is_array($key)) {
                $rs = array();
                foreach ($key as $v) {
                    $post = $_GET[$v];
                    if (isset($post)) {
                        $rs[$v] = $post;
                    }
                }
                return $rs;
            } else {
                return $_GET[$key];
            }
        }
    }

    /*
     * 将key=>value转换为数组字符串
     */
    public static function disposeList($keys, $vals) {
        $l = count($keys);
        if($l < 1){
            return "";
        }
        $i = 0;
        $rs = array();
        while ($i < $l) {
            $rs[$keys[$i]] = urlencode(str_replace("\r\n", "<br/>", $vals[$i]));
            $i++;
        }
        return json_encode($rs);
    }

    public static function unDisposeList($val){
        return str_replace("<br/>", "\r\n", json_decode(urldecode($val),true));
    }

    /*
     * 保存数据
     * @param {string}  $tb 表名
     * @param {array}   $data 保存或更新的数据数组
     * @param {int}     $type 保存草稿（0）或者保存、更新新页面的类型标识（1），默认为1
     * @param {string}  $k 索引的关键字段
     */

    public static function saveDoc($tb, $data, $k = 'p_filename="p_filename"') {
        $rs = PDbconnect::query('select * from ' . $tb . ' where ' . $k);
        if (empty($rs)) {
            // 插入
            if (PDbconnect::insert($tb, $data)) {
                return true;
            } else {
                return false;
            }
        } else {
            // 更新
            if (PDbconnect::update($tb, $data, $k)) {
                return true;
            } else {
                return false;
            }
        }
    }

    /*
     * 删除文档和数据
     * @param {string} $tb 表名
     */
    public static function delDoc($tb, $k = 'p_filename="p_filename"'){
        $rs = PDbconnect::query('select * from ' . $tb . ' where ' . $k);
        if (empty($rs)) {
            return false;
        } else {
            PDbconnect::delete($tb, $k);
            return $rs;
        }
    }

    /*
     * 替换代码中的关键字
     */
    public static function replaceKeys($search, $str, $cls = false){
        if(!is_array($search)){
            return false;
        }
        $pattern = array();
        $replacement = array();
        foreach ($search as $v){
            array_push($pattern, '/' . $v . '/');
            array_push($replacement,  '<span class="' . ($cls ? $cls : 'pk-code-key') . '">' . $v . '</span>');
        }
        return preg_replace($pattern, $replacement, $str);
    }


    /*
     * 补齐序号为3位数：000-999
     */
    public static function fillNumber($num){
        if($num < 10){
            return "00$num";
        }else if($num < 100){
            return "0$num";
        }else{
            return "$num";
        }
    }
}